"""
增强版卖出信号检查器（统一入口/门面）
"""
import logging
from typing import Tuple, Optional, Dict
from datetime import datetime
import pandas as pd

from .base import ValidationContext
from .engine import SignalConfirmationEngine
from .analyzers import (
    StockLiquidityAnalyzer,
    TimeSensitivityAnalyzer,
    AbnormalMarketDetector
)

logger = logging.getLogger('EnhancedSellSignalChecker')


class EnhancedSellSignalChecker:
    """
    增强版卖出信号检查器（统一入口）
    集成流动性分析、敏感度分析、异常检测和信号确认
    """
    
    def __init__(self, config: Dict = None):
        """
        Args:
            config: 配置字典（可选）
        """
        self.confirmation_engine = SignalConfirmationEngine(config)
        self.liquidity_analyzer = StockLiquidityAnalyzer()
        self.sensitivity_analyzer = TimeSensitivityAnalyzer()
        
        logger.info("增强版卖出信号检查器初始化完成")
    
    def check_sell_signal(self, 
                         stock_data: pd.DataFrame, 
                         current_index: int,
                         current_time: datetime, 
                         sell_reason: str,
                         stock_code: Optional[str] = None,
                         position_info: Optional[Dict] = None) -> Tuple[bool, str]:
        """
        检查卖出信号（统一入口）
        
        Args:
            stock_data: 股票数据DataFrame
            current_index: 当前索引
            current_time: 当前时间
            sell_reason: 卖出原因
            stock_code: 股票代码（可选）
            position_info: 持仓信息（可选，用于止损计算）
            
        Returns:
            Tuple[bool, str]: (是否应该卖出, 详细原因)
        """
        try:
            # 1. 检测异常市场条件
            abnormalities = AbnormalMarketDetector.detect_abnormal_conditions(
                stock_data, current_index
            )
            
            # 处理异常情况
            abnormal_result = self._handle_abnormal_conditions(abnormalities, sell_reason)
            if abnormal_result:
                return abnormal_result
            
            # 2. 流动性分类
            liquidity = self.liquidity_analyzer.classify(
                stock_data, current_index, stock_code
            )
            
            # 3. 敏感度分析
            sensitivity = self.sensitivity_analyzer.analyze(current_time, liquidity)
            
            # 4. 构建验证上下文
            context = ValidationContext(
                stock_data=stock_data,
                current_index=current_index,
                current_time=current_time,
                sell_reason=sell_reason,
                liquidity=liquidity,
                sensitivity=sensitivity,
                stock_code=stock_code,
                position_info=position_info
            )
            
            # 5. 信号确认
            confirmed, details = self.confirmation_engine.validate_signal(context)
            
            # 6. 不在这里输出日志，由回测系统统一输出（避免重复）
            return confirmed, details
            
        except Exception as e:
            logger.error(f"信号检查异常: {e}", exc_info=True)
            # 异常情况下谨慎处理，放行信号
            return True, f"{sell_reason} | 检查异常，放行信号"
    
    def _handle_abnormal_conditions(self, 
                                   abnormalities: Dict, 
                                   sell_reason: str) -> Optional[Tuple[bool, str]]:
        """
        处理异常市场条件
        
        Args:
            abnormalities: 异常条件字典
            sell_reason: 卖出原因
            
        Returns:
            Optional[Tuple[bool, str]]: 如果需要特殊处理返回结果，否则返回None
        """
        if not abnormalities:
            return None
        
        # 跌停板：立即卖出（如果能成交）
        if abnormalities.get('limit') == 'down':
            logger.warning(f"🚨 检测到跌停板，立即卖出")
            return True, f"{sell_reason} | 跌停板，立即卖出"
        
        # 集合竞价时段：延迟处理
        if abnormalities.get('call_auction'):
            logger.debug("⏸️ 集合竞价时段，延迟处理")
            return False, "集合竞价时段，延迟处理"
        
        # 成交量异常放大：降低确认要求（市场活跃）
        if abnormalities.get('volume_surge'):
            logger.debug("📈 成交量异常放大，降低确认要求")
            # 这里不直接返回，而是让后续流程处理，但会影响敏感度
            # 可以在context中添加这个信息
        
        # 成交量异常萎缩：提高警惕
        if abnormalities.get('volume_dry'):
            logger.debug("📉 成交量异常萎缩，提高确认要求")
        
        return None  # 继续正常验证流程
    
    def get_statistics(self) -> Dict:
        """
        获取统计信息
        
        Returns:
            Dict: 统计数据
        """
        return self.confirmation_engine.get_statistics()
    
    def print_statistics(self):
        """打印统计信息"""
        self.confirmation_engine.print_statistics()
    
    def reset_statistics(self):
        """重置统计信息"""
        self.confirmation_engine.reset_statistics()
    
    def register_custom_validator(self, name: str, validator):
        """
        注册自定义验证器（扩展接口）
        
        Args:
            name: 验证器标识
            validator: 验证器实例
        """
        self.confirmation_engine.register_validator(name, validator)
        logger.info(f"注册自定义验证器: {name}")

